#!/bin/bash
set -exuo pipefail

export ONBUILD=${DOCKER_REPO}-onbuild
export DEMO=${DOCKER_REPO}-demo
export REPOS="${DOCKER_REPO} ${ONBUILD} ${DEMO}"
# push ONBUILD image
docker push $ONBUILD:$DOCKER_TAG
docker push $DEMO:$DOCKER_TAG

function get_hub_version() {
  rm -f hub_version
  docker run --rm -v $PWD:/version -u $(id -u) -i $DOCKER_REPO:$DOCKER_TAG sh -c 'jupyterhub --version > /version/hub_version'
  hub_xyz=$(cat hub_version)
  split=( ${hub_xyz//./ } )
  hub_xy="${split[0]}.${split[1]}"
  # add .dev on hub_xy so it's 1.0.dev
  if [[ ! -z "${split[3]:-}" ]]; then
    hub_xy="${hub_xy}.${split[3]}"
    latest=0
  else
    latest=1
  fi
}

get_hub_version

for repo in ${REPOS}; do
  # when building master, push 0.9.0.dev as well
  docker tag $repo:$DOCKER_TAG $repo:$hub_xyz
  docker push $repo:$hub_xyz

  # when building 0.9.x, push 0.9 as well
  docker tag $repo:$DOCKER_TAG $repo:$hub_xy
  docker push $repo:$hub_xy

  # if building a stable release, tag latest as well
  if [[ "$latest" == "1" ]]; then
    docker tag $repo:$DOCKER_TAG $repo:latest
    docker push $repo:latest
  fi
done
